<template>
    <div>
        <div class="address" @click="toaddr">{{address}}</div>
        <div class="empty" v-if="carts.length === 0">
            　　　　　　　　购物车空空如也，快去选购商品吧
            <br><br>
            <van-button type="info" class="btn_shopping" @click="gotoshop()">选购商品</van-button>
        </div>
        <div class="noempty" v-else>
            <template>
                <div @click="removecart()">
                    删除
                </div>
            </template>
            <div class="carts">
                <van-card
                v-for="cart in carts"
                :key="cart.id"
                :num="cart.number"
                :desc="cart.specs"
                >
                    <template #thumb>
                        <van-checkbox @change="checkedOne()" v-model="cart.checked"></van-checkbox>
                        <img :src="cart.banner" />
                    </template>
                    <template #title>
                        <b>{{cart.name}}</b>
                    </template>
                    <template #price>
                        <span style="color: red;">￥{{cart.price}}</span>
                    </template>
                    <template #num>
                        <van-button @click="reduceNum(cart.id)" round size="mini" plain type="info">-</van-button>
                        <span class="pronum">{{cart.number}}</span>
                        <van-button @click="addNum(cart.id)" round size="mini" type="danger">+</van-button>
                    </template>
                    <template #bottom>
                        <br>
                        小计： <span>￥{{cart.subtotal}}</span> 
                    </template>
                    <template #price-top>
                        <span @click="del(cart.id)" class="remove">×</span>
                    </template>
                </van-card>
            </div>
            <div class="jiesuan">
                <div class="settle">
                    <van-checkbox @click="checkedAll()" v-model="checkAll">全选</van-checkbox>
                    <div class="text">
                        <p>实付：￥{{finalprice.toFixed(2)}}</p>
                        <p>已优惠：￥{{discount.toFixed(2)}}</p>
                    </div>
                    <van-button round plain @click="payfor()">去结算（{{totalNum}}）</van-button>
                </div>
            </div>
        </div>
        <myfooter />
    </div>
</template>

<script>
import Vue from 'vue';
import { Card, GridItem } from 'vant';
import  myfooter from '@/components/myfooter'
import { Checkbox, CheckboxGroup } from 'vant';
import { Button } from 'vant';
import {getcart,editCart,delCart, operate,getDefaultAddr,delall,getmoney,setmoney,towaitsend,towaitpay} from '@/request'
import { Toast } from 'vant';
import {Dialog} from 'vant'
import {getcookie} from '@/utils/cookie'


Vue.use(Toast);
Vue.use(Button);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Card);
export default {
    components:{
        myfooter:myfooter
    },
    data() {
    return {
      carts:[],
      checkAll:false,
      address:'',
      show:false,
      money:0,
    };
  },
  created(){
        var username = getcookie('username')
        if(!username) {
            localStorage.setItem('url', '/cart')
            this.$router.push('/my/login')
        }
        getcart().then(data => {
            this.carts = data.map(item => {
                // 每个商品的选中状态
                item.checked = false
                // 小计
                item.subtotal = operate(item.price, item.number, '*')
                return item
            })
        })
        getDefaultAddr().then(data=>{
            console.log(data)
            if(data.code===1)
            {
                this.address = data.data.name + ',' + data.data.tel + ',' + data.data.address
            }else{
                this.address = '请移步添加地址'
            }
        })
  },
  computed:
  {
        totalPrice()
        {
           var carts = this.carts.filter(item=>item.checked)
           var n = 0
           carts.forEach(item=>{
                n+=item.subtotal
           })
           return n
        },
        totalNum()
        {
          var carts = this.carts.filter(item=>item.checked)
          var n = 0
          carts.forEach(item=>n+=item.number)
          return n 
        },
        discount()
        {
            var carts = this.carts.filter(item=>item.checked)
            var n = 0
            carts.forEach(item=>{
                n+=item.subtotal
           })
           n = operate(n,0.05,'*')
           return n
        },
        finalprice()
        {
            var carts = this.carts.filter(item=>item.checked)
            var n = 0
            var m = 0
            carts.forEach(item=>{
                n+=item.subtotal
           })
           m = operate(n,0.05,'*')
           return operate(n,m,'-')
        }
  },
  methods:
  {
 
      addNum(id)
      {
        var cart = this.carts.find(Item=>Item.id === id)
        cart.number++
        cart.subtotal = operate(cart.price,cart.number,'*')
        editCart(cart).then(data=>{
                console.log(data)
        })
      },
      reduceNum(id)
      {
        var cart = this.carts.find(Item=>Item.id === id)
        cart.number--
        if(cart.number === 0)
        {
            var index = this.carts.find(Item=>Item.id === id)
            this.carts.splice(index,1)
            delCart(id).then(data=>{

            })

        }else{
            cart.subtotal = operate(cart.price,cart.number,'*')
            editCart(cart).then(data=>{
            console.log(data)
        })
        }
        
      },
      checkedAll(){
        this.carts.forEach(item=>{
                item.checked = this.checkAll
        })
      },
      checkedOne()
      {
         this.checkAll = this.carts.every(item => item.checked)
      },
      del(id)
      //询问用户
      {
         Dialog.confirm({
                title:'购物车删除',
                message:'您真的要删除这个商品吗'
         })
         .then(()=>{
                var index = this.carts.findIndex(item=>item.id === id)
                this.carts.splice(index,1)
                delCart(id).then(data=>{
                    Toast.success(data.msg);
                })
         })
         .catch(()=>{
                Toast.success('已取消！')
         })
      },
    toaddr()
    {
        this.$router.push('/address')
    },
    gotoshop()
    {
        this.$router.push('/types')
    },
    payfor()
    {
        getmoney().then(data=>{
            if(data.money)
            {
                this.money = data.money
            }
             
        })
        if(this.totalNum === 0)
        {
            return
        }
        var carts = this.carts.filter(item=>item.checked)
         Dialog.confirm({
                title:'确认支付',
                message:'你确定要支付商品吗?',
            })
            .then(()=>{
                console.log(this.money)
                if(operate(this.money,this.finalprice,'-')>=0)
                {
                    this.money = operate(this.money,this.finalprice,'-')
                    console.log(this.money.toFixed(2))
                    Toast.success('支付成功')
                    towaitsend(carts)
                    setmoney(this.money).then(data=>{
                        console.log(data)
                    })
                }else{
                    Toast.fail('余额不足,支付失败,请充值')
                    towaitpay(carts)
                        
                }
                delall(carts)
                })
                .catch(()=>{
                Toast.fail('已取消')
                towaitpay(carts)
    })
            
         
 },
//  删除选中的购物车
    removecart()
    {
        var carts = this.carts.filter(item=>item.checked)
        if(carts.length===0)
        {
            return
        }
        Dialog.confirm({
                title:'确认删除',
                message:'你确定要删除该购物车的商品吗?',
            })
            .then(()=>{
                delall(carts)
                Toast.success('已删除成功')
                })
                .catch(()=>{
                Toast.fail('已取消')
            })
    }
    }
    }

 
</script>

<style>
.carts img{
    width: 80px;
    height: 100px;
    margin-left: 40px;
}
.carts .van-checkbox{
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
}
.van-card__thumb{
    width: 130px;
}
.van-card__num .van-button{
    width: 20px;
    height: 20px;
    font-size: 18px;
    vertical-align: top;
}
.pronum{
    margin: 0 10px;
    font-size: 16px;
}
.van-card__content>div:first-child{
    margin-right: 170px;
}
.van-card__num{
    margin-right: 100px;
}
.remove{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 0;
    font-size: 20px;
    padding: 10px;
}
.jiesuan{
    position: fixed;
    bottom: 50px;
    left: 0;
    width: 100%;
    background-color: #f00;
}
.settle{
    display: flex;
    justify-content: space-between;
    padding: 10px 20px;
    align-items: center;
    color: #fff;
}
.settle .van-checkbox__label{
    color: #fff;
}
.settle .text{
    flex: 1;
    padding-left: 20px;
}
.settle .text p{
    padding: 0;
    margin: 0;
}
.address 
{
    padding:10px 20px;
    text-align:center;
    border-bottom: 2px solid #ccc;
}
.shopping
{
    padding: 110px;
    margin-top: 200px;
}
.btn_shopping
{
    margin-left: 200px;
}
.pay span
{
    padding:40px;
    bottom: 10px;
}
</style>